<template>
    <view>
        <view style="padding-bottom: 140rpx">
			<j-cell-group>
			    <j-cell title="录像开关" :more="false">
				    <view slot="tips">
					    <switch :checked="videoCheck" @change="bindchangeVideo"></switch>
				    </view>
			    </j-cell>
			</j-cell-group >
			<j-cell-group v-if="videoCheck">
				<j-cell title="录像长度(分种)" sub-title="单个录像文件最长的时间" :more="false">
				    <view slot="tips" style="width: 50vw;">
						<slider :value="recordList[channel].PacketLength" min="1" max="120" @change="changePacketLength" show-value style="margin:0;"/>
					</view>
				</j-cell>
				<j-cell-card title="录像音频" sub-title="如果关闭,则录下来的文件没有音频" :show="false" :is-touch="false" :more="false">
					<view slot="tips">
						<switch :checked="audioEnables.MainFormat.AudioEnable" @change="changeMainFormatAudioEnable"></switch>
					</view>
					<!-- <j-cell title="主码流" :more="false">
						<view slot="tips">
							<switch :checked="audioEnables.MainFormat.AudioEnable" @change="changeMainFormatAudioEnable"></switch>
						</view>
					</j-cell>
				    <j-cell title="辅码流" :more="false">
				    	<view slot="tips">
				    		<switch :checked="audioEnables.ExtraFormat.AudioEnable" @change="changeExtraFormatAudioEnable"></switch>
				    	</view>
				    </j-cell> -->
				</j-cell-card>
				<j-cell-card title="录像画质" :show="false" :is-touch="false" :tips="videolable">
					<template v-for="(item, index) in qualityList">
					    <j-cell :key="index" :title="item.text" :more="false" @jftap="jftapMainFormatVideoQuality(index,item.text)">
					        <view slot="tips" v-if="item.value === audioEnables.MainFormat.Video.Quality">
								<uni-icons custom-prefix="iconfont" type="icon-duihao" size="24" color="#FF0025"></uni-icons>
					        </view>
					    </j-cell>
					</template>
					<!-- <j-cell-card title="主码流" :show="false" :is-touch="false" border style="background: #F5F7FB;">
						<template v-for="(item, index) in qualityList">
						    <j-cell :key="index" :title="item.text" :more="false" @jftap="jftapMainFormatVideoQuality(index)">
						        <view slot="tips" v-if="item.value === audioEnables.MainFormat.Video.Quality">
									<uni-icons custom-prefix="iconfont" type="icon-duihao" size="24" color="#FF0025"></uni-icons>
						        </view>
						    </j-cell>
						</template>
					</j-cell-card>
					<j-cell-card title="辅码流" :show="false" :is-touch="false" border style="background: #F5F7FB;">
						<template v-for="(item, index) in qualityList">
						    <j-cell :key="index" :title="item.text" :more="false" @jftap="jftapExtraFormatVideoQuality(index)">
						        <view slot="tips" v-if="item.value === audioEnables.ExtraFormat.Video.Quality">
									<uni-icons custom-prefix="iconfont" type="icon-duihao" size="24" color="#FF0025"></uni-icons>
						        </view>
						    </j-cell>
						</template>
					</j-cell-card> -->
				</j-cell-card>
			</j-cell-group>
			
            <j-cell-group>
                <!-- <j-cell-card title="通道" :tips="channel + 1" :show="false" :is-touch="false" :more="false" border style="background: #f5f7fb">
                    <template v-for="(item, index) in recordList">
                        <j-cell :key="index" title="1" :more="false" @jftap="bindtapChannel(index)">
                            <view slot="tips" v-if="index === channel">
								<uni-icons custom-prefix="iconfont" type="icon-duihao" size="24" color="#FF0025"></uni-icons>
                            </view>
                        </j-cell>
                    </template>
                </j-cell-card> -->
					<!-- <j-cell title="冗余" :more="false">
					    <view slot="tips">
					        <switch :checked="recordList[channel].Redundancy" @change="bindchangeRedundancy"></switch>
					    </view>
					</j-cell> -->
					
					<!-- <j-cell title="预录(秒)" sub-title="值为0时表示关闭预录" :more="false">
					    <view slot="tips" style="width: 50vw;">
							<slider :value="recordList[channel].PreRecord" min="0" max="30" @change="changePreRecord" show-value style="margin:0;"/>
					    </view>
					</j-cell> -->
					
					<!-- <j-cell-card title="录像模式" :is-touch="false" :more="false">
						<view slot="tips">
							<uni-data-checkbox mode="tag" v-model="recordMode" :localdata="recordModeList" selected-color="#FF0025" @change="changeRecordMode"></uni-data-checkbox>
						</view>
					</j-cell-card> -->
					
					<j-cell-card v-show="false" title="录像工作表" :show="false" :is-touch="false" border v-if="recordList[channel].RecordMode === 'ConfigRecord'">
					    <view style="border-bottom: 1px solid #eeeeee">
					        <picker :value="week" :range="weeks" @change="bindchangeWeeks">
					            <view style="display: flex; justify-content: space-between; align-items: center; background: #ffffff; padding: 20rpx">
					                <view>星期</view>
					                <view>
										{{ weeks[week] }}
										<view class="arrow"></view>
									</view>
					            </view>
					        </picker>
					    </view>
					    <view style="border-bottom: 1px solid #eeeeee" v-for="(item, index) in timeMaskList" :key="index">
					        <picker mode="multiSelector" :value="item.time" :range="[hours, minutes, hours, minutes]" @change="bindchangeTime($event,index)">
					            <view style="display: flex; justify-content: space-between; align-items: center; background: #ffffff; padding: 20rpx">
					                <view>时间段{{ index + 1 }}</view>
					                <view>
										{{ hours[item.time[0]] }}:{{ minutes[item.time[1]] }} -- {{ hours[item.time[2]] }}:{{ minutes[item.time[3]] }}
										<view class="arrow"></view>
									</view>
					            </view>
					        </picker>
					
					        <checkbox-group @change="bindchangeMask($event, index)" style="display: flex; justify-content: space-around; align-items: center; padding: 20rpx 0">
					            <label>
					                <checkbox value="1" :checked="item.mask[0] === 1" />
					                普通
					            </label>
					            <label>
					                <checkbox value="2" :checked="item.mask[1] === 1" />
					                检测
					            </label>
					            <label>
					                <checkbox value="3" :checked="item.mask[2] === 1" />
					                报警
					            </label>
					        </checkbox-group>
					    </view>
					</j-cell-card>
				
            </j-cell-group>
        </view>

        <view class="bottom-fixed">
            <button type="primary" class="block radius-btn" @tap="bindtapSave">保存</button>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            token: '',
			// 当前录像模式
			recordMode:0,
			// 录像模式集合
			recordModeList:[
				{text:'配置',mode:'ConfigRecord',value:0},
				{text:'手动',mode:'ManualRecord',value:1},
				{text:'关闭',mode:'ClosedRecord',value:2}
			],
			// record集合
            recordList: [],
			// 画质集合
			qualityList:[
				{text:'很差',value:1},
				{text:'较差',value:2},
				{text:'一般',value:3},
				{text:'好',value:4},
				{text:'很好',value:5},
				{text:'最好',value:6},
			],
			// 通道
            channel: 0,
			// 录像音频
			audioEnables:{},
            weeks: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '全部'],
            week: 0,
            hours: ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24'],
            minutes: [
                '00',
                '01',
                '02',
                '03',
                '04',
                '05',
                '06',
                '07',
                '08',
                '09',
                '10',
                '11',
                '12',
                '13',
                '14',
                '15',
                '16',
                '17',
                '18',
                '19',
                '20',
                '21',
                '22',
                '23',
                '24',
                '25',
                '26',
                '27',
                '28',
                '29',
                '30',
                '31',
                '32',
                '33',
                '34',
                '35',
                '36',
                '37',
                '38',
                '39',
                '40',
                '41',
                '42',
                '43',
                '44',
                '45',
                '46',
                '47',
                '48',
                '49',
                '50',
                '51',
                '52',
                '53',
                '54',
                '55',
                '56',
                '57',
                '58',
                '59'
            ],
            timeMaskList: [],
			videoCheck:false,
			videolable:''
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {
		this.token = options.token
		this.week = new Date().getDay()
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
		this.getconfig();
	},
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    methods: {
        getconfig() {
            uni.showLoading();
            let token = this.token;
            let data = {
                Name: 'Record'
            };
            getApp().globalData.api.getconfig(data, token, (result) => {
                uni.hideLoading()
                        console.log('=========111',result);
						this.recordList = result['Record']
						// 定位录像模式
						if(this.recordList && this.recordList.length > 0 && this.recordList[this.channel].RecordMode){
							this.recordMode = this.enumeration(this.recordList[this.channel].RecordMode)
						}
						this.recordList[0].Mask.forEach((item,index)=>{
							if(item[0].substring(0, 3) == '0x7'){
								this.videoCheck = true
							}else if(item[0].substring(0, 3) == '0x6'){
								this.videoCheck = false
							}
						})
						// 定位录像工作表
						if (this.week <= 6) {
						    this.TimeSectionMaskTo(this.week);
						} else {
						    for (let i = 0; i < 7; i++) {
						        this.TimeSectionMaskTo(i);
						    }
						}
						
						this.getconfigSimplifyEncode()
                    
                
            });
        },
		getconfigSimplifyEncode() {
		    uni.showLoading();
		    let token = this.token;
		    let data = {
		        Name: 'Simplify.Encode'
		    };
		    getApp().globalData.api.getconfig(data, token, (result) => {
		        uni.hideLoading()
						console.log('=========222',result);
						this.audioEnables = result['Simplify.Encode'][this.channel]
						this.qualityList.forEach((item,index)=>{
							if(item.value == this.audioEnables.MainFormat.Video.Quality){
								this.videolable = item.text
							}
						})
		            
		    });
		},
		// 录像总开关
		bindchangeVideo(ev){
			console.log(ev)
			this.videoCheck = ev.detail.value;
			this.recordList[0].Mask.forEach((item,index)=>{
				if(ev.detail.value){
					item[0] = item[0].replace(item[0].substring(0, 3), '0x7')
				}else{
					item[0] = item[0].replace(item[0].substring(0, 3), '0x6')
				}
			})
			console.log(this.recordList[0].Mask)
		},
		changeMainFormatAudioEnable(ev){
			this.audioEnables.MainFormat.AudioEnable = ev.detail.value
			this.setconfigSimplifyEncode()
		},
		changeExtraFormatAudioEnable(ev){
			this.audioEnables.ExtraFormat.AudioEnable = ev.detail.value
			this.setconfigSimplifyEncode()
		},
		jftapMainFormatVideoQuality(ev,text){
			this.audioEnables.MainFormat.Video.Quality = ev + 1
			this.videolable = text
			this.setconfigSimplifyEncode()
		},
		jftapExtraFormatVideoQuality(ev){
			this.audioEnables.ExtraFormat.Video.Quality = ev + 1
			this.setconfigSimplifyEncode()
		},
        // 通道
        bindtapChannel(ev) {
			console.log(ev);
            // this.channel = Number(ev);
			this.getconfig();
        },

        // 冗余
        bindchangeRedundancy(ev) {
            this.recordList[this.channel].Redundancy = ev.detail.value;
        },

        // 长度
		changePacketLength(ev){
			this.recordList[this.channel].PacketLength = ev.detail.value;
		},

        // 预录
		changePreRecord(ev){
			this.recordList[this.channel].PreRecord = ev.detail.value
		},

        // 配置模式
		changeRecordMode(ev){
			if(ev.detail.value === 0){
				this.recordMode = 0
			}else if(ev.detail.value === 1){
				this.recordMode = 1
			}else if(ev.detail.value === 2){
				this.recordMode = 2
			}
			this.recordList[this.channel].RecordMode = this.recordModeList[this.recordMode].mode
		},
		/**
		 * @description 根据返回的值获取recordModeList集合中的value值
		 * @param {String} value recordMode模式
		 */
		enumeration(value){
			for (let i = 0; i < this.recordModeList.length; i++) {
				if(this.recordModeList[i].mode === value){
					return this.recordModeList[i].value
					break
				}
			}
		},

        // 星期
        bindchangeWeeks(ev) {
			this.week = Number(ev.detail.value)
			this.TimeSectionMaskTo(this.week);
        },

        // 时间段
        bindchangeTime(ev,index) {
            console.log(ev, this.timeMaskList);
            // let index = index;
            let value = ev.detail.value;

            for (let i = 0; i < this.timeMaskList.length; i++) {
                const item = this.timeMaskList[i];

                if (i === index) {
                    item.time = value;
                    break;
                }
            }
			
			if (this.week <= 6) {
			    this.ToTimeSectionMask(this.week);
			} else {
			    for (let i = 0; i < 7; i++) {
			        this.ToTimeSectionMask(i);
			    }
			}
        },

        // mask
        bindchangeMask(ev,index) {
            console.log(ev, this.timeMaskList);
            // let index = index;
            let value = ev.detail.value;
            let maskArray = [1, 1, 1];

            if (value.length <= 0) {
                maskArray = [0, 0, 0];
            } else {
                if (!value.includes('1')) {
                    maskArray[0] = 0;
                }

                if (!value.includes('2')) {
                    maskArray[1] = 0;
                }

                if (!value.includes('3')) {
                    maskArray[2] = 0;
                }
            }

            for (let i = 0; i < this.timeMaskList.length; i++) {
                const item = this.timeMaskList[i];

                if (i === index) {
                    item.mask = maskArray;
                    break;
                }
            }

            if (this.week <= 6) {
                this.ToTimeSectionMask(this.week);
            } else {
                for (let i = 0; i < 7; i++) {
                    this.ToTimeSectionMask(i);
                }
            }
        },

        /** ================================================ TimeSection 和 Mask 的转换 ===================================================== */
        // 传参转本地
        TimeSectionMaskTo(week) {
            let record = this.recordList[this.channel]; // 获取某通道数据

            let timeSectionList = record.TimeSection; // TimeSection集合

            let maskList = record.Mask; // Mask集合

            let timeSectionArray = timeSectionList[week]; // 星期几的TimeSection（6个时间段）

            let maskArray = maskList[week]; // 星期几的Mask（6个时间段对应的mask选项）

            let timeMaskList = [];
            timeSectionArray.forEach((item, index) => {
                maskArray.forEach((pro, size) => {
                    if (index === size) {
                        let timeArray = this.TimeSectionTo(item);
                        let maskArray = this.MaskTo(pro);
                        timeMaskList.push({
                            time: timeArray,
                            mask: maskArray
                        });
                    }
                });
            });
            this.timeMaskList = timeMaskList
        },

        // 本地转传参
        ToTimeSectionMask(week) {
            let maskArray = [];
            let timeArray = [];
            this.timeMaskList.forEach((item, index) => {
                maskArray.push(this.ToMask(item.mask));

                if (index === 0) {
                    timeArray.push('1 ' + this.ToTimeSection(item.time));
                } else {
                    timeArray.push('0 ' + this.ToTimeSection(item.time));
                }
            });
            this.recordList[this.channel].Mask[week] = maskArray;
            this.recordList[this.channel].TimeSection[week] = timeArray;
        },

        // 返回的时间格式转换为本地时间格式
        TimeSectionTo(str) {
            let arr1 = str.split(' ');
            let prefix = arr1[0];
            let suffix = arr1[1];
            let arr2 = suffix.split('-');
            let start = arr2[0];
            let end = arr2[1];
            let arr3 = start.split(':');
            let startHour = arr3[0];
            let startMinute = arr3[1];
            let startSecond = arr3[2];
            let arr4 = end.split(':');
            let endHour = arr4[0];
            let endMinute = arr4[1];
            let endSecond = arr4[2];
            let timeArray = [];

            for (let i = 0; i < this.hours.length; i++) {
                const item = this.hours[i];

                if (item === startHour) {
                    timeArray.push(i);
                }
            }

            for (let i = 0; i < this.minutes.length; i++) {
                const item = this.minutes[i];

                if (item === startMinute) {
                    timeArray.push(i);
                }
            }

            for (let i = 0; i < this.hours.length; i++) {
                const item = this.hours[i];

                if (item === endHour) {
                    timeArray.push(i);
                }
            }

            for (let i = 0; i < this.minutes.length; i++) {
                const item = this.minutes[i];

                if (item === endMinute) {
                    timeArray.push(i);
                }
            }

            return timeArray;
        },

        // 本地时间格式转换为参数需要的时间格式
        ToTimeSection(timeArray) {
            let str = '';
            let startHour = this.hours[timeArray[0]];
            let startMinute = this.minutes[timeArray[1]];
            let endHour = this.hours[timeArray[2]];
            let endMinute = this.minutes[timeArray[3]];
            str = startHour + ':' + startMinute + ':00-' + endHour + ':' + endMinute + ':00';
            return str;
        },

        // 返回的Mask格式转换为本地Mask格式
        MaskTo(str) {
            let maskArray = [];

            if (str === '0x00000007') {
                maskArray = [1, 1, 1];
            } else if (str === '0x00000006') {
                maskArray = [0, 1, 1];
            } else if (str === '0x00000005') {
                maskArray = [1, 1, 0];
            } else if (str === '0x00000004') {
                maskArray = [0, 1, 0];
            } else if (str === '0x00000003') {
                maskArray = [1, 0, 1];
            } else if (str === '0x00000002') {
                maskArray = [0, 0, 1];
            } else if (str === '0x00000001') {
                maskArray = [1, 0, 0];
            } else if (str === '0x00000000') {
                maskArray = [0, 0, 0];
            }

            return maskArray;
        },

        // 本地的mask格式转换为参数需要的Mask
        ToMask(maskArray) {
            let str = '';

            if (JSON.stringify(maskArray) === '[1,1,1]') {
                str = '0x00000007';
            } else if (JSON.stringify(maskArray) === '[0,1,1]') {
                str = '0x00000006';
            } else if (JSON.stringify(maskArray) === '[1,1,0]') {
                str = '0x00000005';
            } else if (JSON.stringify(maskArray) === '[0,1,0]') {
                str = '0x00000004';
            } else if (JSON.stringify(maskArray) === '[1,0,1]') {
                str = '0x00000003';
            } else if (JSON.stringify(maskArray) === '[0,0,1]') {
                str = '0x00000002';
            } else if (JSON.stringify(maskArray) === '[1,0,0]') {
                str = '0x00000001';
            } else if (JSON.stringify(maskArray) === '[0,0,0]') {
                str = '0x00000000';
            }

            return str;
        },

        bindtapSave(ev) {
            this.setconfig();
        },

        // 设置配置
        setconfig() {
            uni.showLoading();
            let token = this.token;
            let data = {
                Name: 'Record',
                Record: this.recordList
            };
            getApp().globalData.api.setconfig(data, token, (result) => {
                uni.showToast({
                    title: '保存成功',
					success: () => {
						uni.navigateBack({
							delta:1
						})
					}
                });
            });
        },
		setconfigSimplifyEncode() {
		    uni.showLoading();
		    let token = this.token;
		    let data = {
		        Name: 'Simplify.Encode',
		        'Simplify.Encode': [this.audioEnables]
		    };
		    getApp().globalData.api.setconfig(data, token, (result) => {
		        uni.showToast({
		            title: '保存成功'
		        });
		    });
		},
    }
};
</script>
<style>
	.arrow {
		display: inline-block;
	    width: 10rpx;
	    height: 10rpx;
	    border-width: 2rpx;
	    border-style: solid;
	    border-color: #666666;
	    border-left-color: transparent;
	    border-bottom-color: transparent;
	    transform: rotate(45deg);
	}
</style>
